package com.rivues.util.datasource;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentMap;

import javax.servlet.http.HttpServletRequest;

import mondrian.olap.Axis;
import mondrian.olap.Cell;
import mondrian.olap.Connection;
import mondrian.olap.Member;
import mondrian.olap.Position;
import mondrian.olap.Query;
import mondrian.olap.Result;
import mondrian.rolap.RolapCubeLevel;
import mondrian.rolap.RolapLevel;
import mondrian.rolap.agg.AggregationManager;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.rivu.tools.TempletTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.model.AnalyzerReportModel;
import com.rivues.module.platform.web.model.Cube;
import com.rivues.module.platform.web.model.CubeLevel;
import com.rivues.module.platform.web.model.CubeMeasure;
import com.rivues.module.platform.web.model.Database;
import com.rivues.module.platform.web.model.Dimension;
import com.rivues.module.platform.web.model.JobDetail;
import com.rivues.module.platform.web.model.QueryLog;
import com.rivues.module.platform.web.model.QueryText;
import com.rivues.module.platform.web.model.ReportFilter;
import com.rivues.module.platform.web.model.SearchResultTemplet;
import com.rivues.module.platform.web.model.User;
import com.rivues.util.RivuTools;
import com.rivues.util.data.CubeData;
import com.rivues.util.data.FirstTitle;
import com.rivues.util.data.Level;
import com.rivues.util.data.ReportData;
import com.rivues.util.data.ValueData;
import com.rivues.util.service.ServiceHelper;
import com.rivues.util.service.cache.CacheHelper;
import com.rivues.util.tools.ExportFile;
import com.rivues.util.tools.StringUtil;

import freemarker.template.TemplateException;

public class CubeTools implements DataSource {
	private final Logger log = LoggerFactory.getLogger(CubeTools.class); 
	private Database database ;
	
	public CubeTools(Database database){
		this.database = database ;
	}
	@Override
	public boolean valid(Cube cube) throws Exception {
		String schemaFileName = createSchemaFile(null , null , cube , null , false , null);
		Connection connection = null ;
		try{
			connection = (Connection) ServiceHelper.getDataSourceService().service(cube , schemaFileName);//RivuDataContext.getConnection(cube);
		}catch(Exception ex){
			System.out.println(ex);
			throw ex;
		}finally{
			if(connection!=null){
				connection.close();
			}
			File schemaFile = new File(schemaFileName) ;
			if(schemaFile.exists()){
				schemaFile.delete() ;
			}
		}
		return true;
	}
	/**
	 * 是否执行除零操作
	 * @param model
	 * @return
	 */
	private String crossJoinType(AnalyzerReportModel model){
		String crossJoinType = "CrossJoin" ;
		if(model!=null && model.isClearzero()){
			crossJoinType = "NonEmptyCrossJoin" ;
		}
		return crossJoinType ;
	}
	/**
	 * 
	 * @param cube
	 * @return
	 */
	private String getCubeFileName(Cube cube) {
		return new StringBuffer().append(RivuDataContext.DATA_DIR).append(File.separator).append("cube").append(File.separator).append(cube.getId()).append(UUID.randomUUID().toString()).append(".xml").toString();
	}
	
	/**
	 * 
	 * @param cube
	 * @return
	 */
	private String getCubeDataFileName(Cube cube) {
		return new StringBuffer().append(RivuDataContext.DATA_DIR).append(File.separator).append("cube").append(File.separator).append("cube_data_").append(RivuTools.md5(cube.getId())).append(UUID.randomUUID().toString())
				.append(".xml").toString();
	}

	/**
	 * 内部方法，生成临时的 Cube 文件
	 * @param model
	 * @param cube
	 * @param request
	 * @param parseParam
	 * @throws Exception 
	 */
	private String createSchemaFile(AnalyzerReportModel model , Map<String , Object> requestParamValues, Cube cube,
			HttpServletRequest request, boolean parseParam , QueryText queryText) throws Exception {
		List<Cube> cubeList = new ArrayList<Cube>();
		cubeList.add(cube) ;
		String fileName = null ;
		if(cube.getCreatedata()!=null && cube.getCreatedata().equals("true")){
			FileUtils.writeStringToFile(new File(fileName = getCubeDataFileName(cube)), createCubeDataSchema(cubeList , cube , queryText) , "UTF-8") ;
		}else{
			FileUtils.writeStringToFile(new File(fileName = getCubeFileName(cube)), createSchema(cubeList , requestParamValues , request, cube , queryText) , "UTF-8") ;
		}
		return fileName ;
	}

	/**
	 * 生成Cube的XML数据文件， 生成文件为 临时文件，使用完毕即关闭
	 * 
	 * @param cube
	 * @return
	 * @throws TemplateException
	 * @throws IOException
	 */
	public static String createSchema(List<Cube> cubeList , Map<String , Object> requestParamValues, HttpServletRequest request , Cube cube , QueryText queryText) throws IOException, Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("cubeList", cubeList);
		data.put("name", cube.getId());
		if(queryText!=null && queryText.getExpress()!=null){
			data.put("express", queryText.getExpress().getConDimList());
		}
		if(requestParamValues!=null){
			data.put("values", requestParamValues) ;
		}
		return TempletTools.getTemplet(
				(SearchResultTemplet) RivuDataContext.getService().getIObjectByPK(SearchResultTemplet.class, "402881e43ab07e65013ab080e4c60002"), data);
	}
	
	/**
	 * 生成Cube的XML数据文件
	 * 
	 * @param cube
	 * @return
	 * @throws TemplateException
	 * @throws IOException
	 */
	public static String createCubeDataSchema(List<Cube> cubeList , Cube cube , QueryText queryText) throws IOException, Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("cubeList", cubeList);
		data.put("name", cube.getId());
		if(queryText!=null && queryText.getExpress()!=null){
			data.put("express", queryText.getExpress().getConDimList());
		}
		return TempletTools.getTemplet(
				(SearchResultTemplet) RivuDataContext.getService().getIObjectByPK(SearchResultTemplet.class, "402881e43da5225d013da532ea880001"), data);
	}
	/**
	 * 生成结算数据SQL
	 * @param model
	 * @param cube
	 * @param request
	 * @param queryLog
	 * @return
	 */
	public String createCubeFilterSQL(AnalyzerReportModel model, Cube cube,
			HttpServletRequest request   , QueryLog queryLog , boolean useStaticFilter){
		StringBuffer strb = new StringBuffer() ;
		StringBuffer wherecon = new StringBuffer();
		List<ReportFilter> reportFilter = model.getFilters() ;
		if(true){
			reportFilter = RivuTools.getStaticFilters(model.getFilters()) ;
		}
		if("true".equals(cube.getCreatedata()) && reportFilter.size()>0){
			for(ReportFilter filter : reportFilter){
				if("range".equals(filter.getValuefiltertype())){//范围   range code_start 和 code_end
					if((filter.getCode()!=null && !StringUtil.isNull(RivuTools.getStartValue(filter , request)) && !StringUtil.isNull(RivuTools.getEndValue(filter , request)))|| (!StringUtil.isNull(RivuTools.getStartValue(filter , request))) && !StringUtil.isNull(RivuTools.getEndValue(filter , request))){
						String startValue = RivuTools.getStartValue(filter , request);
						String endValue = RivuTools.getEndValue(filter , request);
						String dataname = "DIM_" + RivuTools.md5(filter.getDataid()!=null?filter.getDataid():"");
						if(StringUtil.isNotNull(startValue) && StringUtil.isNotNull(endValue)){
							wherecon.append(wherecon.length()>0?" and ":"").append(filter.getFilterprefix()!=null && filter.getFilterprefix().length()>0 ? filter.getFilterprefix():"").append(dataname.toUpperCase()).append(filter.getFiltersuffix()!=null && filter.getFiltersuffix().length()>0 ? filter.getFiltersuffix():"").append(" <= ").append(filter.getFilterprefix()!=null && filter.getFilterprefix().length()>0 ? filter.getFilterprefix():"").append("'").append(endValue).append("'").append(filter.getFiltersuffix()!=null && filter.getFiltersuffix().length()>0 ? filter.getFiltersuffix():"").append(" and ").append(filter.getFilterprefix()!=null && filter.getFilterprefix().length()>0 ? filter.getFilterprefix():"").append(dataname.toUpperCase()).append(filter.getFiltersuffix()!=null && filter.getFiltersuffix().length()>0 ? filter.getFiltersuffix():"").append(" >=").append(filter.getFilterprefix()!=null && filter.getFilterprefix().length()>0 ? filter.getFilterprefix():"").append("'").append(startValue).append("' ").append(filter.getFiltersuffix()!=null && filter.getFiltersuffix().length()>0 ? filter.getFiltersuffix():"");
						}
					}else{
						String startValue = "";
						String endValue = "";
						String dataname = "DIM_" + RivuTools.md5(filter.getDataid()!=null?filter.getDataid():"");
						if(StringUtil.isNotNull(startValue) && StringUtil.isNotNull(endValue)){
							wherecon.append(wherecon.length()>0?" and ":"").append(dataname.toUpperCase()).append(" <= '").append(endValue).append("'").append(" and ").append(dataname).append(" >= '").append(startValue).append("' ");
						}
					}
				}else{//compare
					String value = RivuTools.getDefaultValue(filter , request);

					String dataname = "DIM_" + RivuTools.md5(filter.getDataid()!=null?filter.getDataid():"");

					if(value==null || "ALL".equals(value.toUpperCase())){

					}else{
						if(!wherecon.toString().contains(dataname)){
							if(StringUtil.isNotNull(value)){
								if(wherecon.length()>0){
									wherecon.append(" and ");
								}
								if("EQUAL".equals(filter.getComparetype().toUpperCase())){
									if(value.indexOf(",")>-1){
										wherecon.append(dataname.toUpperCase()).append(" in ('").append(value.replaceAll(",", "','")).append("') ");
									}else{
										wherecon.append(dataname.toUpperCase()).append(" = '").append(value).append("' ");
									}
								}else if("NOT".equals(filter.getComparetype().toUpperCase())){
									if(value.indexOf(",")>-1){
										wherecon.append(dataname.toUpperCase()).append(" not in ('").append(value.replaceAll(",", "','")).append("') ");
									}else{
										wherecon.append(dataname.toUpperCase()).append(" != '").append(value).append("' ");
									}
								}
							}
						}
					}
				}
			}
		}
		if(wherecon.length()>0){
			strb.append(" select * from ").append(cube.getTable().toUpperCase());
			if(wherecon.length() > 0){
				strb.append(" where ").append(wherecon);
			}else{
				strb.append(cube.getTable()) ;
			}
		}
		return strb.length()>0 ? strb.toString() : null ;
	}
	/**
	 * 生成过滤条件用
	 */
	@Override
	public QueryText getQuery(AnalyzerReportModel model, Cube cube,
			HttpServletRequest request   , CubeLevel level , String addCondition , QueryLog queryLog , boolean useStaticFilter , ReportFilter filter) {
		/**
		 * 构建CUBE的过滤器，针对 结算数据有效
		 */
		cube.setSql(createCubeFilterSQL(model, cube, request, queryLog , useStaticFilter)) ;
		QueryText query = new QueryText();
		StringBuffer strb = new StringBuffer() , dimCon = new StringBuffer();
		strb.append("SELECT ") ;
		
		StringBuffer measure = new StringBuffer();
		for (int i= 0 ; i<1 ; i++) {
			CubeMeasure cm  = cube.getMeasure().get(0) ;
			measure.append("[Measures].[" + ("1".equals(cm.getModeltype()) && cm.getMeasure()!=null && !cm.isCalculatedmember() ? cm.getMeasure().getName(): cm.getName()) + "]");
		}
		strb.append(measure.toString()).append(" ON COLUMNS ");
		if(addCondition!=null && addCondition.length()>0){
			dimCon.append(addCondition).append(".Children ") ;
		}else{
			Dimension dim = null ; 
			for(Dimension tempDim : cube.getDimension()){
				for(CubeLevel cubeLevel : tempDim.getCubeLevel()){
					if(level!=null && cubeLevel.getId().equals(level.getId())){
						dim = tempDim ; 
						break ;
					}
				}
				if(dim!=null){
					break ;
				}
			}
			if(level!=null){
				dimCon.append("[").append(dim.getName()).append("].[").append(level.getName()).append("].MEMBERS ") ;
			}
		}
		strb.append(" , ").append(dimCon).append(" ON ROWS ") ;
		strb.append(" FROM [").append(cube.getName()).append("]");
		if(filter!=null && filter.getQueryText()!=null && filter.getQueryText().length()>0){
			if(filter.getQueryText().indexOf("$")>=0){
				query.setQueryText(processParam(filter.getQueryText() , cube , model , request , true , query)) ;;
			}else{
				query.setQueryText(filter.getQueryText()) ;
			}
		}else{
			query.setQueryText(strb.toString()) ;
			filter.setQueryText(strb.toString());
		}
		query.setNativeQueryText(strb.toString()) ;
		StringBuffer queryLogStr = new StringBuffer();
		/**
		 * 记录日志，先判断当前用户是否登录
		 */
		if(queryLog!=null){
			if(request!=null && request.getSession().getAttribute(RivuDataContext.USER_SESSION_NAME)!=null){
				User user = (User) request.getSession().getAttribute(RivuDataContext.USER_SESSION_NAME) ;
				queryLogStr.append(queryLog.getOrgi()).append("/").append(queryLog.getFlowid()).append("/").append(user.getId()).append("/").append(user.getUsername()).append(" ") ;
				queryLogStr.append(strb) ;
				log.info(queryLogStr.toString());
			}else{
				queryLogStr.append(queryLog.getOrgi()).append("/").append(queryLog.getFlowid()).append(" ").append(queryLogStr.toString()) ;
				log.info(queryLogStr.toString());
			}
		}
		
		return query;
	}
	/**
	 * 
	 * @param report
	 * @return
	 */
	public QueryText getQuery(AnalyzerReportModel model , Cube cube , HttpServletRequest request , boolean parseParam , QueryLog queryLog) {
		
		/**
		 * 构建CUBE的过滤器，针对 结算数据有效
		 */
		cube.setSql(createCubeFilterSQL(model, cube, request, queryLog , true)) ;
		
		ConditionExpress express = new ConditionExpress() ;
		QueryText query = new QueryText();
		CubeMDX cubeMdx = new CubeMDX();
		
		List<Dimension> tempDimList = new ArrayList<Dimension>();
		tempDimList.addAll(cube.getDimension()) ;
		
		StringBuffer strb = new StringBuffer() , colstrb = new StringBuffer();
		if(model.getQuerytext()!=null && model.getQuerytext().length()>0){
			strb.append(model.getQuerytext()) ;
			if(model.getFilterstr()!=null && model.getFilterstr().length()>0){
				if(strb.toString().toLowerCase().indexOf("where")>0){
					strb.append(" , (").append(model.getFilterstr()).append(")") ;
				}else{
					strb.append(" where ").append(" (").append(model.getFilterstr()).append(")") ;
				}
			}
			cubeMdx.setMdxstr(strb.toString()) ;
		}else{
			StringBuffer rankStr = new StringBuffer() , rankCon = new StringBuffer();
			if(RivuTools.getRequestFilters(model.getFilters())!=null && RivuTools.getRequestFilters(model.getFilters()).size()>0){
				
				for(ReportFilter filter : RivuTools.getRequestFilters(model.getFilters())){
					StringBuffer randim = new StringBuffer() ;
					if(filter.getFuntype()!=null && filter.getFuntype().equals(RivuDataContext.FilteFunType.RANK.toString())){
						for(Dimension dim : tempDimList){
							for(CubeLevel level : dim.getCubeLevel()){
								if(level.getId().equals(filter.getDataid())){
									randim.append(" [").append(dim.getName()).append("].[").append(level.getName()).append("].CurrentMember") ;
									randim.append(" , ").append("[").append(dim.getName()).append("].[").append(level.getName()).append("].AllMembers ") ;
								}
							}
						}
						for(CubeMeasure measure : cube.getMeasure()){
							if(measure.getId().equals(filter.getMeasureid())){
								if(rankStr.length()==0){
									rankStr.append("WITH ") ;
								}
								rankStr.append(" MEMBER [Measures].[").append(filter.getName()).append("] AS 'RANK( ").append(randim.toString()).append("  , [Measures].[").append(measure.getName()).append("] )'").append("\n") ;
								if(rankCon.length()>0){
									rankCon.append(" , ") ;
								}
								rankCon.append("[Measures].[").append(filter.getName()).append("]") ;
								break ;
							}
						}
					}
				}
			}
			if(rankStr.length()>0){
				strb.append(rankStr.toString()) ;
			}
			strb.append("SELECT ") ;
			String[] dimes = model.getColdimension()!=null && model.getColdimension().length()>0 ? model.getColdimension().split(";") : null;
			
			StringBuffer measure = new StringBuffer();
			if (model.getMeasure() != null && model.getMeasure().length() > 0) {
				String[] meansures = model.getMeasure().split(",");
				int index = 0;
				for (String meansure : meansures) {
					for (CubeMeasure cm : cube.getMeasure()) {
						if (cm.getId().equals(meansure)) {
							if (index > 0) {
								measure.append(",");
							}
							measure.append("[Measures].[" + ("1".equals(cm.getModeltype()) && cm.getMeasure()!=null && !cm.isCalculatedmember() ? cm.getMeasure().getName(): cm.getName()) + "]");
							index++;
							break;
						}
					}
				}
//				if(meansures.length>1){
//					measure.append("}") ;
//				}
			}else{
				if(cube.getMeasure()!=null&&cube.getMeasure().size()>0){
					for (int i= 0 ; i<1 ; i++) {
						CubeMeasure cm  = cube.getMeasure().get(0) ;
						measure.append("[Measures].[" + ("1".equals(cm.getModeltype()) && cm.getMeasure()!=null && !cm.isCalculatedmember() ? cm.getMeasure().getName(): cm.getName()) + "]");
					}
				}
				
			}
			if(measure.length()>0){
				measure.insert(0, "{") ;
				if(rankCon.length()>0){
					if(measure.length()>0){
						measure.append(" , ");
					}
					measure.append(" ").append(rankCon.toString()) ;
				}
				measure.append("}") ;
			}
			boolean hasColumns = false ;
			if(dimes!=null && dimes.length>0 && measure.length()>0){
				hasColumns = true ;
				createCondition(model.getColdimension() , tempDimList , true , model , request  , query , "col" , express) ;
				colstrb.append(" ").append(crossJoinType(model)).append("(").append(express.getCondition()).append(",").append(measure.toString()).append(") ").append(getExchange(model , " ON COLUMNS " , hasColumns)) ;
			}else if(dimes!=null && dimes.length>0){
				hasColumns = true ;
				createCondition(model.getColdimension() , tempDimList , true  , model , request  , query , "col" , express) ;
				colstrb.append(express.getCondition()).append(getExchange(model , " ON COLUMNS " , hasColumns)); 
			}else if(measure.length()>0){
				hasColumns = true ;
				colstrb.append(measure.toString()).append(getExchange(model , " ON COLUMNS " , hasColumns));
			}
			if(colstrb.length()>0){
				strb.append(colstrb.toString()) ;
			}
			createCondition(model.getRowdimension() , tempDimList , true , model , request  , query , "row" , express) ;
			String rowcon = express.getCondition() ;
			if(rowcon.length()>0){
				strb.append(colstrb.length()>0 ?  " , " : "").append(rowcon).append(getExchange(model , " ON ROWS " , hasColumns)) ;
			}
			
			strb.append(" FROM [").append(cube.getName()).append("]");
			/**
			 * WHERE 条件重构，有 Filter未出现在行列里 的时候，需要加入到 WHERE
			 */
			StringBuffer whereCon = new StringBuffer();
			/**
			 * 重构 WHERE条件，如果发现有 下级过滤条件，则加入到 Filter列表中
			 */
			if(express.getQueryFilterValuetList().size()>0){
				model.getFilters().addAll(express.getQueryFilterValuetList()) ;
			}
			if(express!=null && express.getConDimList().size()>0){
				tempDimList.addAll(express.getConDimList()) ;
			}
			if(RivuTools.getRequestFilters(model.getFilters())!=null){
				StringBuffer colRowCon = new StringBuffer();
				for (Dimension dimension : tempDimList){
					for (CubeLevel level : "1".equals(dimension.getModeltype()) ? dimension.getDim().getCubeLevel() : dimension.getCubeLevel()) {
						if((model.getColdimension()!=null && model.getColdimension().indexOf(level.getId())>=0) || (model.getColdimension()!=null && model.getRowdimension().indexOf(level.getId())>=0)){
							colRowCon.append(dimension.getId()) ;
						}
					}
//					if(colRowCon.toString().indexOf(dimension.getId())>=0){
//						break ;
//					}
				}
				for(ReportFilter filter : RivuTools.getRequestFilters(model.getFilters())){
					/**
					 * 还需要检查 是否有同分组下的 过滤条件，如果存在需要忽略
					 */
					for (Dimension dimension : tempDimList){
						int levelDepth = 0 ;
						for (CubeLevel level : "1".equals(dimension.getModeltype()) ? dimension.getDim().getCubeLevel() : dimension.getCubeLevel()) {
							levelDepth++;
							if(filter.getDataid().equals(level.getId()) && colRowCon.toString().indexOf(dimension.getId())<0){
								if(whereCon.length()>0){
									whereCon.append(",") ;
								}
								whereCon.append(filter.getDataid()) ;
								break ;
							}
							if(filter.getDimid()!=null && filter.getDimid().equals(dimension.getId()) && colRowCon.indexOf(filter.getDimid())<0){
								StringBuffer beforLevel = new StringBuffer();
								for(String filterCon : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request).split(RivuDataContext.DEFAULT_VALIUE_SPLIT)){
									int depth = filterCon.split("\\.").length - 1 ;
									if(depth>levelDepth){
										beforLevel = new StringBuffer();
										levelDepth = depth ;
									}
									if(beforLevel.length()>0){
										beforLevel.append(",") ;
									}
									beforLevel.append(level.getId()) ;
								}
								if(whereCon.length()>0){
									whereCon.append(",") ;
								}
								whereCon.append(beforLevel.toString()) ;
							}
						}
					}
				}
			}
			if(whereCon.length()>0){
				strb.append(" WHERE ").append(createCondition(whereCon.toString(), tempDimList , true , model , request  , query , "where" , express).getCondition()) ;
			}
			model.setTempquey(strb.toString()) ;
			
		}
		/**
		 * 替换位置，如果设置为行列转换，则要求必须有列存在
		 */
		if(strb.indexOf(" ON COLUMNS")<0 && strb.indexOf(" ON ROWS")>=0){
			strb.replace(strb.indexOf(" ON ROWS"), strb.indexOf(" ON ROWS")+" ON ROWS".length(), " ON COLUMNS") ;
		}
		String mdx = strb.toString() ;
		if(mdx.indexOf("$")>=0){
			mdx = processParam(mdx , cube , model , request , parseParam , query);
		}
		StringBuffer queryLogStr = new StringBuffer();
		/**
		 * 记录日志，先判断当前用户是否登录
		 */
		if(queryLog!=null){
			queryLogStr.append("[").append(queryLog.getOrgi()).append("/").append(queryLog.getFlowid()).append("/").append(queryLog.getUserid()).append("/").append(queryLog.getUsername()).append("] ") ;
			queryLogStr.append(queryLog.getDataname()).append(" MDX:").append(mdx) ;
			log.info(queryLogStr.toString());
		}else{
			queryLogStr.append("[SYSTEM").append("/").append("SYSTEM]").append(" ").append(queryLogStr.toString()) ;
			log.info(mdx);
		}
		query.setQueryText(mdx) ;
		/**
		 * 下级 过滤，需要重新生成 Schema
		 */
		query.setExpress(express) ;
		return query;
	}
	
	private String getExchange(AnalyzerReportModel model , String type , boolean hasColumns){
		String rowOrCol = type ;
		if(model.isExchangerw() && hasColumns){
			if(type.toLowerCase().indexOf("row")>0) {
				rowOrCol = " ON COLUMNS " ;
			}
			if(type.toLowerCase().indexOf("columns")>0) {
				rowOrCol = " ON ROWS " ;
			}
		}
		return rowOrCol;
	}
	
	public String processParam(String value , Cube cube , AnalyzerReportModel model , HttpServletRequest request , boolean parseParam , QueryText queryText ){
		/**
		 * 一下替换 模板
		 */
		try {
			Map<String , Object> valueMap = new HashMap<String , Object>();
			if(parseParam&&request.getParameterNames()!=null){
				Enumeration<String> param = request.getParameterNames() ;
				while(param.hasMoreElements()){
					String name = param.nextElement() ;
					if(request.getParameter(name)!=null && request.getParameter(name).trim().length()>0){
						valueMap.put(name, request.getParameter(name)) ;
					}
				}
			}
			int p = parseParam?Integer.parseInt(request.getParameter("p") !=null && request.getParameter("p").matches("[\\d]{1,}") ? request.getParameter("p") :"1") :1;
			
			int ps = parseParam?(request.getParameter("ps") !=null && request.getParameter("ps").matches("[\\d]{1,}") ? Integer.parseInt(request.getParameter("ps")) :model.getPageSize()<1?20:model.getPageSize()):model.getPageSize()<1?20:model.getPageSize();
			if(p<1){
				p = 1;
			}
			if(ps<1){
				ps =20 ;
			}
			if(queryText!=null){
				queryText.setP(p) ;
				queryText.setPs(ps) ;
			}
			valueMap.put("p", p) ;
			valueMap.put("ps", ps) ;
			valueMap.put("startindex", (p-1) * ps) ;
			if(parseParam){
				valueMap.put("request",request) ;
			}
			valueMap.put("user", request.getSession(true)==null?new User():request.getSession(true).getAttribute(RivuDataContext.USER_SESSION_NAME)) ;
			valueMap.put("model", model) ;
			value = RivuTools.getTemplet(value, valueMap) ;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
		return value ;
	}
	
	private ConditionExpress createCondition(String conexp , List<Dimension> dimensionList,boolean usesubset , AnalyzerReportModel model , HttpServletRequest request , QueryText queryText , String leveltype , ConditionExpress express){
		StringBuffer subset = new StringBuffer();
		StringBuffer constr = new StringBuffer();
		List<QueryDim> dimList = new ArrayList<QueryDim>();
		Map<String , ReportFilter> reportDimFilterMap = new HashMap<String , ReportFilter>();
		
		if(RivuTools.getRequestFilters(model.getFilters())!=null){
			for(ReportFilter filter : RivuTools.getRequestFilters(model.getFilters())){
				reportDimFilterMap.put(filter.getDataid() , filter) ;
				reportDimFilterMap.put(filter.getDimid() , filter) ;//
			}
		}
//		List<Dimension> tempDimList = new ArrayList<Dimension>();
//		tempDimList.addAll(cube.getDimension()) ;
//		if(express!=null && express.getConDimList().size()>0){
//			tempDimList.addAll(express.getConDimList()) ;
//		}
		
		if(conexp.indexOf(";")<0){
			/**
			 * 修正顺序开始
			 */
//			boolean find = false ;
//			StringBuffer strb = new StringBuffer() ; 
//			for (Dimension dimension : dimensionList){
//				for (CubeLevel level : dimension.getCubeLevel()) {
//					if (conexp.indexOf(level.getId())>=0) {
//						if(strb.length()>0){
//							strb.insert(0, ",") ;
//						}
//						strb.insert(0, level.getId()) ;
//					}
//				}
//				if(find){
//					break ;
//				}
//			}
//			conexp = strb.toString();
			/**
			 * 修正顺序结束
			 */
			for(String col:conexp.split(",")){
				boolean founddim = false ;
				for (Dimension dimension : dimensionList){
					int inx = 0 ;
					for (CubeLevel level : "1".equals(dimension.getModeltype()) ? dimension.getDim().getCubeLevel() : dimension.getCubeLevel()) {
						inx ++ ;
						if (level.getId().equals(col)) {
							founddim = true ;
							boolean found = false ;
							QueryDim queryDim = null ;
							for(QueryDim dim : dimList){
								if(dim.getDimid().equals(dimension.getId())){
									found = true ;
									queryDim = dim ;
									break ;
								}
							}
							if(!found){
								dimList.add(new QueryDim(dimension.getId() , col , inx)) ;
							}else{//同一个分组只允许出现一次
//								if(queryDim.getConstr()==null || queryDim.getConstr().indexOf(col)<0){
//									if(queryDim.getConstr()!=null && queryDim.getConstr().length()>0){
//										queryDim.setConstr(new StringBuffer().append(queryDim.getConstr()).append(",").append(col).toString()) ;
//									}else{
//										queryDim.setConstr(new StringBuffer().append(col).toString()) ;
//									}
//								}
								if(inx>queryDim.getIndex()){
									queryDim.setConstr(col) ;
								}
							}
							break ;
						}
					}
					if(founddim){
						break ;
					}
				}
			}
			for(QueryDim queryDim : dimList){
				if(constr.length()>0){
					constr.append(";") ;
				}
				constr.append(queryDim.getConstr()) ;
			}
			conexp = constr.toString() ;
		}
		int num = 0 ;
//		boolean hasubset = false ;
		if (conexp != null && conexp.length() > 0) {
			String[] dimes = conexp.split(";");
			for (int diminx = 0 ; diminx < dimes.length ; diminx++) {
				String dim = dimes[diminx] ;
				if(dim.length()>0){
					if(num>0){
						subset.insert(0 , crossJoinType(model)+"(") ;
						subset.append(",") ;
					}
					String[] cols = dim.split(",") ;
					if(cols.length>1){
						subset.append("{");
					}
					boolean found = false;
					for(int colindex=0 ; colindex<cols.length ; colindex++){
						if(colindex > 0 ){
							subset.append(" , ") ;
						}
						String col = cols[colindex] ;
						boolean findParent = false ;
						int parentLevel = 0 ;
						boolean foundDim  = false ;
						boolean findCurAndParent = false ;
						for(Dimension filterDim : dimensionList){
							parentLevel = 0 ;
							findCurAndParent = false ;
							findParent = false ;
							for (CubeLevel level : "1".equals(filterDim.getModeltype()) ? filterDim.getDim().getCubeLevel() : filterDim.getCubeLevel()) {
								if(reportDimFilterMap.get(level.getId())!=null){
									findCurAndParent = true ;
								}
								
								if(col.equals(level.getId())){
									foundDim = true ;
									break ;
								}
								if(reportDimFilterMap.get(level.getId())!=null){
									findParent = true ;
								}
								parentLevel++;
							}
							if(foundDim){
								break ;
							}
						}
						for (int i=0 ; i<dimensionList.size() ; i++){
							Dimension dimension  = dimensionList.get(i) ;
							if(col.length()>0){
								int levelIndex = 0 ;
								StringBuffer childStringBuffer = new StringBuffer() ;
								List<CubeLevel> levelList =  "1".equals(dimension.getModeltype()) ? dimension.getDim().getCubeLevel() : dimension.getCubeLevel() ;
								for (CubeLevel level : levelList) {
									levelIndex++ ;
									if (level.getId().equals(col)) {
										found = true ;
										int curLevelIndex = levelList.indexOf(level) ;
										
										if(childStringBuffer.length() > 0 ){
											childStringBuffer.append(",");
										}
										StringBuffer selectFilter = new StringBuffer() ;
										/**
										 * 以下处理 选择过滤条件 ， 从 维度过滤树上选择 ， 需要区分 级别上和 级别下 问题
										 */
										ReportFilter reportFilter = reportDimFilterMap.get(level.getId()) ;
										/**
										 * 分两种情况，一种是 比较，一种是范围 , 两种情况下，都会执行以下IF部分代码
										 */
										String defaultValue = null ;
										String startValue = null ;
										String endValue = null ;
										if(reportFilter!=null){
											defaultValue = RivuTools.getDefaultValue(reportFilter, request);
											startValue = RivuTools.getStartValue(reportFilter, request);
											endValue = RivuTools.getEndValue(reportFilter, request);
										}
										if(reportFilter==null || (RivuDataContext.ReportCompareEnum.COMPARE.toString().equals(reportFilter.getValuefiltertype()) && (defaultValue==null || defaultValue.length() ==0)) || (RivuDataContext.ReportCompareEnum.RANGE.toString().equals(reportFilter.getValuefiltertype()) && ((startValue==null || startValue.length()==0) && (endValue == null || endValue.length() == 0)) )){
											for(int curInx = 0 ; curInx < curLevelIndex ; curInx++){
												CubeLevel tempLevel = levelList.get(curInx) ;
												if(reportDimFilterMap.get(tempLevel.getId())!=null){
													reportFilter = reportDimFilterMap.get(tempLevel.getId()) ;
												}
												defaultValue = null ;
												startValue = null ;
												endValue = null ;
												if(reportFilter!=null){
													defaultValue = RivuTools.getDefaultValue(reportFilter, request);
													startValue = RivuTools.getStartValue(reportFilter, request);
													endValue = RivuTools.getEndValue(reportFilter, request);
												}
												if(reportFilter!=null && ((RivuDataContext.ReportCompareEnum.COMPARE.toString().equals(reportFilter.getValuefiltertype()) && (defaultValue!=null && defaultValue.length() ==0)) || (RivuDataContext.ReportCompareEnum.RANGE.toString().equals(reportFilter.getValuefiltertype()) && ((startValue!=null && startValue.length()>0) || (endValue != null && endValue.length() > 0)) ))){
													break ;
												}
											}
										}
										ReportFilter tempReportFilter = reportFilter!=null ? reportFilter  :reportDimFilterMap.get(dimension.getId()) ;
										if(tempReportFilter!=null && tempReportFilter.getConvalue()!=null && tempReportFilter.getConvalue().equals(RivuDataContext.FilterConValueEnum.AUTO.toString())&&(tempReportFilter.getCurvalue()==null||(tempReportFilter.getCurvalue()!=null&&tempReportFilter.getCurvalue().trim().startsWith("[")&&tempReportFilter.getCurvalue().trim().endsWith("]")))){
											StringBuffer beforLevel = new StringBuffer();
											int levelDepth = 0 ;
											boolean userChild = false ;
											String filterValues = RivuDataContext.ReportCompareEnum.COMPARE.toString().equals(tempReportFilter.getValuefiltertype()) ? RivuTools.getDefaultValue(tempReportFilter  , request) : RivuTools.getStartValue(tempReportFilter , request) ;
											for(String filter : filterValues.split(RivuDataContext.DEFAULT_VALIUE_SPLIT)){
												if(filter.length()>0){
													int depth = filter.split("\\.").length - 1 ;
													if(depth>levelDepth && depth <= levelIndex){
														beforLevel = new StringBuffer();
														levelDepth = depth ;
													}
													if(depth <= levelIndex){
														if(beforLevel.length()>0){
															beforLevel.append(",") ;
														}
														beforLevel.append(filter) ;
													}else{
														
														//下级过滤
														if(depth>0){
															userChild = true ; 
															break ;
														}
													}
												}
											}
											/**
											 * 下级过滤条件，重新生成一个 DIM，然后将此DIM动态的加入到  Schema中去
											 */
											if(userChild){
												beforLevel = new StringBuffer();
												try {
													ReportFilter childReportFilter = (ReportFilter) RivuTools.toObject(RivuTools.toBytes(tempReportFilter) ) ;
													childReportFilter.setChild(true) ;
													Dimension otherDim = (Dimension) RivuTools.toObject(RivuTools.toBytes(dimension) );
													otherDim.setChild(true) ;
													otherDim.setName(RivuDataContext.CHILD_DIM_PREFIX+otherDim.getName()) ;
													
													otherDim.setId(RivuDataContext.CHILD_DIM_PREFIX+otherDim.getId()) ;
													for(CubeLevel childLevel : otherDim.getCubeLevel()){
														childLevel.setChildid(childLevel.getId()) ;
														childLevel.setId(RivuDataContext.CHILD_DIM_PREFIX+childLevel.getId()) ;
													}
													childReportFilter.setId(RivuDataContext.CHILD_DIM_PREFIX+childReportFilter.getId()) ;
													childReportFilter.setDimid(RivuDataContext.CHILD_DIM_PREFIX+childReportFilter.getDimid()) ;
													childReportFilter.setDataid(RivuDataContext.CHILD_DIM_PREFIX+childReportFilter.getDataid()) ;
													childReportFilter.setRequestvalue(null) ;
													childReportFilter.setValuefiltertype(tempReportFilter.getValuefiltertype()) ;
													if(RivuDataContext.ReportCompareEnum.COMPARE.toString().equals(tempReportFilter.getValuefiltertype())){
														childReportFilter.setDefaultvalue(processChildValue(RivuTools.getDefaultValue(tempReportFilter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request) , tempReportFilter , RivuDataContext.ReportCompareEnum.COMPARE.toString())) ;
													}else{
														childReportFilter.setRequeststartvalue(processChildValue(RivuTools.getDefaultValue(tempReportFilter , RivuDataContext.ReportCompareEnum.START.toString() , request) , tempReportFilter , RivuDataContext.ReportCompareEnum.COMPARE.toString())) ;
														childReportFilter.setRequestendvalue(processChildValue(RivuTools.getDefaultValue(tempReportFilter , RivuDataContext.ReportCompareEnum.END.toString() , request) , tempReportFilter , RivuDataContext.ReportCompareEnum.COMPARE.toString())) ;
													}
													childReportFilter.setValuefiltertype(tempReportFilter.getValuefiltertype()) ;
													express.getConDimList().add(otherDim) ;
													express.getQueryFilterValuetList().add(childReportFilter) ;
												} catch (Exception e) {
													e.printStackTrace();
												}
												
											}
											StringBuffer ptl = new StringBuffer();
											for( int lpt = 0 ; lpt < (levelIndex -levelDepth) && levelDepth>0 ; lpt++){
												ptl.append(".parent") ;
											}
											if(RivuDataContext.ReportCompareEnum.COMPARE.toString().equals(tempReportFilter.getValuefiltertype())){
												if(beforLevel.length()>0){
													selectFilter.append("Filter([").append(dimension.getName()).append("].[" ).append( level.getName() ).append("].AllMembers , ").append(" [").append(dimension.getName()).append("].[" ).append( level.getName() ).append("].CurrentMember").append(ptl.toString()).append(RivuDataContext.FilterCompType.EQUAL.toString().equals(tempReportFilter.getComparetype()) ? " IN " : " NOT IN ").append("{").append(beforLevel.toString()).append("})");
												}else{
//													selectFilter.append("[").append(dimension.getName()).append("].[" ).append( level.getName() ).append("].AllMembers");
												}
											}else{
												if(beforLevel.length()>0){
													selectFilter.append(tempReportFilter.getRequeststartvalue()).append(":").append(tempReportFilter.getRequestendvalue());
												}else{
//													selectFilter.append("[").append(dimension.getName()).append("].[" ).append( level.getName() ).append("].AllMembers");
												}
											}
											childStringBuffer.append(selectFilter.toString());
										}else{
											/**
											 * 需要首先判断下是否有下级，判断方式为
											 */
											if(findCurAndParent == false&&tempReportFilter!=null){//执行此操作的前提是过滤器不能为空
												try {
													ReportFilter childReportFilter = (ReportFilter) RivuTools.toObject(RivuTools.toBytes(tempReportFilter) ) ;
													childReportFilter.setChild(true) ;
													Dimension otherDim = (Dimension) RivuTools.toObject(RivuTools.toBytes(dimension) );
													otherDim.setChild(true) ;
													otherDim.setName(RivuDataContext.CHILD_DIM_PREFIX+otherDim.getName()) ;
													
													otherDim.setId(RivuDataContext.CHILD_DIM_PREFIX+otherDim.getId()) ;
													for(CubeLevel childLevel : otherDim.getCubeLevel()){
														childLevel.setChildid(childLevel.getId()) ;
														childLevel.setId(RivuDataContext.CHILD_DIM_PREFIX+childLevel.getId()) ;
													}
													childReportFilter.setId(RivuDataContext.CHILD_DIM_PREFIX+childReportFilter.getId()) ;
													childReportFilter.setDimid(RivuDataContext.CHILD_DIM_PREFIX+childReportFilter.getDimid()) ;
													childReportFilter.setDataid(RivuDataContext.CHILD_DIM_PREFIX+childReportFilter.getDataid()) ;
													childReportFilter.setRequestvalue(null) ;
													childReportFilter.setConvalue(tempReportFilter.getConvalue()) ;
													if(RivuDataContext.ReportCompareEnum.COMPARE.toString().equals(tempReportFilter.getValuefiltertype())){
														childReportFilter.setDefaultvalue(processChildValue(RivuTools.getDefaultValue(tempReportFilter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request) , tempReportFilter , RivuDataContext.ReportCompareEnum.COMPARE.toString())) ;
													}else{
														childReportFilter.setRequeststartvalue(processChildValue(RivuTools.getDefaultValue(tempReportFilter , RivuDataContext.ReportCompareEnum.START.toString() , request) , tempReportFilter , RivuDataContext.ReportCompareEnum.COMPARE.toString())) ;
														childReportFilter.setRequestendvalue(processChildValue(RivuTools.getDefaultValue(tempReportFilter , RivuDataContext.ReportCompareEnum.END.toString() , request) , tempReportFilter , RivuDataContext.ReportCompareEnum.COMPARE.toString())) ;
													}
													childReportFilter.setValuefiltertype(tempReportFilter.getValuefiltertype()) ;
													express.getConDimList().add(otherDim) ;
													express.getQueryFilterValuetList().add(childReportFilter) ;
												} catch (Exception e) {
													e.printStackTrace();
												}
											}
											if(selectFilter.length() == 0 ){
												selectFilter.append("[").append(dimension.getName()).append("].[" ).append( level.getName() ).append("].AllMembers");
											}
											if(findParent){
												int inx = 0 ;
												StringBuffer strb = new StringBuffer() ;
												String dimName = ("1".equals(dimension.getModeltype()) ? dimension.getDim() : dimension).getName() ;
												for (CubeLevel tmpLevel : "1".equals(dimension.getModeltype()) ? dimension.getDim().getCubeLevel() : dimension.getCubeLevel()) {
													if(reportDimFilterMap.get(tmpLevel.getId())!=null){
														StringBuffer currentParent = new StringBuffer();
														currentParent.append("[").append(dimName).append("].[").append(level.getName()).append("].CurrentMember") ;
														for(int levelNum = 0 ; levelNum<(parentLevel-inx) ; levelNum++){
															currentParent.append(".parent") ;
														}
														if(strb.length()>0){
															strb.append(" AND ");
														}
	
														ReportFilter filter = reportDimFilterMap.get(tmpLevel.getId()) ; 
														/**
														 * 可以从 request 里使用 id 或者 code 获取参数值， 如果 使用id 获取值为空，则使用 code 
														 */
														String conname = (filter.getCode()!=null && request.getParameter(filter.getCode())!=null) ? filter.getCode() : filter.getId() ;
														
														
														if(filter.getValuefiltertype()!=null && "range".equals(filter.getValuefiltertype())){
															strb.append(filter.getComparetype().equals("not")? " NOT ":"").append("compare(").append(currentParent.append(".name")) ;
														}else{
															strb.append(currentParent.append(".name")) ;
														}
														
														
														
														String startParam = new StringBuffer().append(conname).append("_start").toString() ;
														String endParam = new StringBuffer().append(conname).append("_end").toString() ;
														
														if((request.getParameterValues(conname)!=null && request.getParameterValues(conname).length>0) 
																|| (filter.getCurstartvalue()!=null && filter.getCurstartvalue().length()>0)
																|| (filter.getCurendvalue()!=null && filter.getCurendvalue().length()>0)
																){
															String[] requestValues = request.getParameterValues(conname) ;
															StringBuffer currentParamValue = new StringBuffer() ;
															if(requestValues!=null){
																for(String value : requestValues){
																	if(currentParamValue.length()>0){
																		currentParamValue.append("|") ;
																	}
																	currentParamValue.append(value) ;
																}
																if(currentParamValue.length()==0){
																	strb = new StringBuffer();
																}else{
																	
																	if(currentParamValue.length()>0&&!currentParamValue.toString().trim().startsWith("[")&&!currentParamValue.toString().trim().endsWith("]")){
																		String temps = currentParamValue.toString();
																		currentParamValue = new StringBuffer(temps.replaceAll(RivuDataContext.DEFAULT_VALIUE_SPLIT, "|"));
																	}
																	if("not".equals(filter.getComparetype())){
																		strb.append(" NOT MATCHES '").append(currentParamValue).append("'") ;
																	}else{
																		strb.append(" MATCHES '").append(currentParamValue).append("'") ;
																	}
																}
															}else{
																String requestValue = (request.getParameter(conname)!=null ? request.getParameter(conname) : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request)!=null ? RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request) : "") ;
																if(requestValue!=null && requestValue.length()>0){
																	strb = new StringBuffer();
																}else{
																	if(filter.getValuefiltertype()!=null && "range".equals(filter.getValuefiltertype())){
																		/**
																		 * 范围查询， id_start 和 id_end
																		 */
																		String start = (request.getParameter(startParam)!=null ? request.getParameter(startParam) : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.START.toString() , request)!=null ? RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.START.toString() , request) : "")  ;
																		String end = (request.getParameter(endParam)!=null ? request.getParameter(endParam) : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.END.toString() , request)!=null ? RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.END.toString() , request) : "")  ;
																		strb.append(" , '' , '").append(start).append("','").append(end).append("')") ;
																		/**
																		 * 如果是范围查询，则使用 compare函数
																		 */
																	}else{
																		strb.append(" = '").append(requestValue).append("'") ;
																	}
																}
															}
															
														}else{
															String requestValue = (request.getParameter(conname)!=null ? request.getParameter(conname) : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request)!=null ? RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request) : "") ;
															if(requestValue.length() == 0 ){
																strb = new StringBuffer();
															}else{
																if(filter.getValuefiltertype()!=null && "range".equals(filter.getValuefiltertype())){
																	/**
																	 * 范围查询， id_start 和 id_end
																	 */
																	String start = (request.getParameter(startParam)!=null ? request.getParameter(startParam) : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.START.toString() , request)!=null ? RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.START.toString() , request) : "")  ;
																	String end = (request.getParameter(endParam)!=null ? request.getParameter(endParam) : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.END.toString() , request)!=null ? RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.END.toString() , request) : "")  ;
																	strb.append(" , '' , '").append(start).append("','").append(end).append("')") ;
																	/**
																	 * 如果是范围查询，则使用 compare函数
																	 */
																	strb.append("") ;
																}else{
//																	if("not".equals(filter.getComparetype())){
//																		strb.append(" <> '").append(requestValue).append("'") ;
//																	}else{
//																		strb.append(" = '").append(requestValue).append("'") ;
//																	}
																	if(!requestValue.toString().trim().startsWith("[")&&!requestValue.toString().trim().endsWith("]")){
																		String temps = requestValue.toString();
																		requestValue = temps.replaceAll(RivuDataContext.DEFAULT_VALIUE_SPLIT, "|");
																	}
																	if("not".equals(filter.getComparetype())){
																		strb.append(" NOT MATCHES '").append(requestValue).append("'") ;
																	}else{
																		strb.append(" MATCHES '").append(requestValue).append("'") ;
																	}
																}
															}
														}
													}
													inx++ ;
												}
												if(strb.length()>0){
													childStringBuffer.append("Filter(").append(selectFilter.toString()).append(", ").append(strb.toString()).append(")");
												}else{
													childStringBuffer.append(selectFilter.toString());
												}
												
											}else if(reportDimFilterMap.get(level.getId())!=null){
												ReportFilter filter = reportDimFilterMap.get(level.getId()) ;
												
												/**
												 * 可以从 request 里使用 id 或者 code 获取参数值， 如果 使用id 获取值为空，则使用 code 
												 */
												String conname = (filter.getCode()!=null && request.getParameter(filter.getCode())!=null) ? filter.getCode() : filter.getId() ;
												
												
												String dimName = ("1".equals(dimension.getModeltype()) ? dimension.getDim() : dimension).getName() ;
												
												String startParam = new StringBuffer().append(conname).append("_start").toString() ;
												String endParam = new StringBuffer().append(conname).append("_end").toString() ;
												if((filter.getCurvalue()!=null && filter.getCurvalue().length()>0) 
														|| (filter.getCurstartvalue()!=null && filter.getCurstartvalue().length()>0)
														|| (filter.getCurendvalue()!=null && filter.getCurendvalue().length()>0)){
													String[] requestValues = request.getParameterValues(conname) ;
													StringBuffer strb = new StringBuffer() ;
													if(requestValues!=null && requestValues.length>1){
														for(String value : requestValues){
															if(strb.length()>0){
																strb.append("|") ;
															}
															strb.append(value) ;
														}
														
														if(strb.length()>0&&!strb.toString().trim().startsWith("[")&&!strb.toString().trim().endsWith("]")){
															String temps = strb.toString();
															strb = new StringBuffer(temps.replaceAll(RivuDataContext.DEFAULT_VALIUE_SPLIT, "|"));
														}
														
														if("not".equals(filter.getComparetype())){
															childStringBuffer.append("Filter(").append(selectFilter.toString()).append(" , [").append(dimName).append("].[").append(level.getName()).append("].CurrentMember.name NOT MATCHES '").append(strb.toString()).append("')");
														}else{
															childStringBuffer.append("Filter(").append(selectFilter.toString()).append(", [").append(dimName).append("].[").append(level.getName()).append("].CurrentMember.name MATCHES '").append(strb.toString()).append("')");
														}
														
													}else{
														if(filter.getValuefiltertype()!=null && "range".equals(filter.getValuefiltertype())){
															/**
															 * 范围查询， id_start 和 id_end
															 */
															String start = (request.getParameter(startParam)!=null ? request.getParameter(startParam) : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.START.toString() , request)!=null ? RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.START.toString() , request) : "")  ;
															String end = (request.getParameter(endParam)!=null ? request.getParameter(endParam) : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.END.toString() , request)!=null ? RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.END.toString() , request) : "")  ;
															strb.append("'").append(start).append("','").append(end).append("'") ;
															/**
															 * 如果是范围查询，则使用 compare函数
															 */
															childStringBuffer.append("Filter(").append(selectFilter.toString()).append(", ").append( filter.getComparetype().equals("not")? " NOT ":"").append(" compare([").append(dimName).append("].[").append(level.getName()).append("].CurrentMember.name ,'', ").append(strb.toString()).append("))");
														}else{
															strb.append(RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request)) ;
															if(strb.length()>0&&!strb.toString().trim().startsWith("[")&&!strb.toString().trim().endsWith("]")){
																String temps = strb.toString();
																strb = new StringBuffer(temps.replaceAll(RivuDataContext.DEFAULT_VALIUE_SPLIT, "|"));
															}
															if("not".equals(filter.getComparetype())){
																childStringBuffer.append("Filter(").append(selectFilter.toString()).append(" , [").append(dimName).append("].[").append(level.getName()).append("].CurrentMember.name NOT MATCHES '").append(strb.toString()).append("')");
															}else{
																childStringBuffer.append("Filter(").append(selectFilter.toString()).append(" , [").append(dimName).append("].[").append(level.getName()).append("].CurrentMember.name MATCHES '").append(strb.toString()).append("')");
															}
														}
													}
												}else{
													String requestValue = request.getParameter(conname)!=null ? request.getParameter(conname) : RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request)!=null ? RivuTools.getDefaultValue(filter , RivuDataContext.ReportCompareEnum.COMPARE.toString() , request) : "" ;
													if(requestValue!=null && requestValue.length()>0){
														if("not".equals(filter.getComparetype())){
															childStringBuffer.append("Filter(").append(selectFilter.toString()).append(" , [").append(dimName).append("].[").append(level.getName()).append("].CurrentMember.name <> '").append(requestValue).append("')");
														}else{
															childStringBuffer.append("Filter(").append(selectFilter.toString()).append(" , [").append(dimName).append("].[").append(level.getName()).append("].CurrentMember.name = '").append(requestValue).append("')");
														}
													}else{
														childStringBuffer.append(selectFilter.toString());
													}
												}
											}else{
												childStringBuffer.append(selectFilter.toString());
											}
											break;
										}
									}
								}
								if(found){
									subset.append(childStringBuffer) ;
								}
							}
						}
//						if(colindex == 0 && "row".equals(leveltype)){
//							
//						}
					}
					if(cols.length>1){
						subset.append("}");
					}
					if(num>0){
						subset.append(")") ;
					}
					num++;
				}
			}
		}
		if(num>0 && usesubset && "row".equals(leveltype)){
			int p = true ? Integer
					.parseInt(request.getParameter("p") != null
							&& request.getParameter("p").matches(
									"[\\d]{1,}") ? request
							.getParameter("p") : "1") : 1;
			int ps = true ? Integer
					.parseInt(request.getParameter("ps") != null
							&& request.getParameter("ps").matches(
									"[\\d]{1,}") ? request
							.getParameter("ps") : "0") : 0;
			if (p < 1) {
				p = 1;
			}
			if (ps < 1) {
				ps = model.getPageSize()>0 ? model.getPageSize() : 20;
			}
			int startindex = (p - 1) * ps;
//			if(model.getCssclassname()!=null && model.getCssclassname().equals("true")){
			subset.insert(0, "subset(").append(",").append(startindex).append(" , ").append(ps).append(")") ;
//			}
			queryText.setP(p) ;
			queryText.setPs(ps) ;
//			hasubset = true ;
		}else if(num>0 && usesubset && "col".equals(leveltype)){
			subset.insert(0, "subset(").append(",").append("0,").append(model.getColSize()!= 0 ? model.getColSize():100).append(")");
		}
		express.setCondition(subset.toString()) ;
		return express;
	}

	
	
	
	
	/**
	 * 处理没有数据的时候也显示表头
	 * @param args
	 */
	public ReportData getData(AnalyzerReportModel model , Map<String , Object> requestParamValues , Cube cube, HttpServletRequest request , boolean parseParam , QueryText queryText  , QueryLog queryLog) throws Exception{
		long start = System.currentTimeMillis() ;
		CubeData cubeData = new CubeData();
		Connection connection = null ;
		String schemaFileName = createSchemaFile(model , requestParamValues , cube , request , parseParam , queryText);
		try{
//			refresh(null, cube);
			replaceDataBase(model,request,parseParam);
			/**
			 * 从服务中获取链接
			 */
			connection = (Connection) ServiceHelper.getDataSourceService().service(cube , schemaFileName);//RivuDataContext.getConnection(cube);
			Query query = connection.parseQuery(queryText.getQueryText());
			Result result = connection.execute(query) ;
			if(queryLog!=null){
				queryLog.setExecutetime(System.currentTimeMillis() - start) ;
			}
			//找了很多地方就是这里有问题 同时createTitle()这个方法再给firsttitle赋值时有问题
			start = System.currentTimeMillis() ;
			Axis[] axises = result.getAxes();
			
	
			cubeData.setData(new ArrayList<List<ValueData>>());
			for (int i = 0; i < axises.length; i++) {
				if (i == 0) {
					cubeData.setCol(createTitle(axises[i], i));
				} else {
					cubeData.setRow(createTitle(axises[i], i));
					cubeData.setTotal(axises[i].getDataSize());
				}
			}
			if(cubeData.getRow()==null){
				cubeData.setRow(new Level("root","row", null , 0)) ;
				cubeData.getRow().setTitle(new ArrayList<List<Level>>());
				if(cubeData.getRow().getTitle().size()==0){
					List<Level> rowList = new ArrayList<Level>() ;
					rowList.add(new Level("合计","row", null , 0)) ;
					cubeData.getRow().getTitle().add(rowList) ;
//					cubeData.getRow().getTitle().add(new ArrayList<Level>()) ;
				}
			}
			getRowData(result.getAxes(), result.getAxes().length - 1, new int[result.getAxes().length], result, cubeData.getData(), 0 , null , cubeData);
			processSum(cubeData.getRow(), cubeData.getData() , cubeData.getRow()) ;
			processSum(cubeData.getCol(), cubeData.getData() , cubeData.getCol()) ;
			cubeData.getRow().setTitle(new ArrayList<List<Level>>()) ;
			processTitle(cubeData.getRow() , cubeData.getRow());
//			processTitle(cubeData.getCol() , cubeData.getCol());
			cubeData.setPage(queryText.getP()) ;
			cubeData.setPageSize(queryText.getPs()) ;
			
			if(model.getStylestr()!=null && model.getStylestr().equals("true")){
				pagetTotalProcess(cubeData , model , cube);
			}
			if(model.getExport()!=null&&model.getExport().getJobDetail()!=null){
				long passed = queryText.getP()*queryText.getPs();
				model.getExport().getJobDetail().getReport().setTotal(cubeData.getTotal());
				model.getExport().getJobDetail().getReport().setPages(passed>=cubeData.getTotal()?cubeData.getTotal():passed);
				model.getExport().getJobDetail().getReport().setStatus(RivuTools.status(model.getExport().getJobDetail()));
				Map<String, Object> jobDetailMap = RivuDataContext.getClusterInstance().get(RivuDataContext.DistributeEventEnum.RUNNINGJOB.toString());
				if(jobDetailMap.get(model.getExport().getJobDetail().getId())!=null){
					jobDetailMap.put(model.getExport().getJobDetail().getId(), model.getExport().getJobDetail());
				}
			}
		}catch(Exception ex){ 
			throw ex;
		}finally{
			if(connection!=null){
				connection.close();
			}
			File schemaFile = new File(schemaFileName) ;
			if(schemaFile.exists()){
				schemaFile.delete();
			}
		}
		if(queryLog!=null){
			queryLog.setDataprocesstime(System.currentTimeMillis()-start);
		}
		
		
		return (ReportData)cubeData;
	}
	/**
	 * 处理下级
	 * @param tempReportFilter
	 * @param vtype
	 * @return
	 */
	private String processChildValue(String value ,ReportFilter tempReportFilter , String vtype){
		StringBuffer childStringBuffer = new StringBuffer();
		if(value.length()>0 && value.length()>1 && RivuDataContext.FilterConValueEnum.AUTO.toString().equals(tempReportFilter.getConvalue())){
			for(String filter : value.split(RivuDataContext.DEFAULT_VALIUE_SPLIT)){
				if(childStringBuffer.length()>0){
					childStringBuffer.append(RivuDataContext.DEFAULT_VALIUE_SPLIT) ;
				}
				childStringBuffer.append(filter.substring(0,1)).append(RivuDataContext.CHILD_DIM_PREFIX).append(filter.substring(1)) ;
			}
		}else{
			childStringBuffer.append(value) ;
		}
		return childStringBuffer.toString() ;
	}

	@SuppressWarnings("rawtypes")
	public static void iterator(Map<String, Map> value, Level level, String leveltype) {
		Iterator<String> iterator = value.keySet().iterator();
		if (level.getChilderen() == null) {
			level.setChilderen(new ArrayList<Level>());
		}
		while (iterator.hasNext()) {
			String name = iterator.next();
			Level sublevel = new Level(name, leveltype , level , level.getDepth()-1);
			level.getChilderen().add(sublevel);
			if (value.get(name) != null) {
				iterator(value.get(name), sublevel, leveltype);
			}
		}
	}
	@SuppressWarnings("rawtypes")
	public Level createTitle(Axis axis, int index) {
		Level level = new Level("root", index == 0 ? "col" : "row" , null , 0);
		Map<String, Map> valueMap = new HashMap<String, Map>();
		List<Position> posList = axis.getPositions();
		List<String> valueStr = new ArrayList<String>();
		List<FirstTitle> firstTitle = new ArrayList<FirstTitle>();
		for (Position pos : posList) {
			StringBuffer strb = new StringBuffer();
			for (int i = 0; i < pos.size(); i++) {
				Member member = pos.get(i);
				RolapLevel cubeLevel = (RolapLevel) member.getLevel();
				int n = 0;
				if(member.getLevel() instanceof RolapCubeLevel && cubeLevel.getName().indexOf("All")<0){
					if(level.getFirstTitle()==null){
						level.setFirstTitle(firstTitle);
						FirstTitle first = new FirstTitle();
						first.setName(cubeLevel.getName());
						first.setLevel(cubeLevel.getUniqueName()) ;
						addFirstTitle(level.getFirstTitle(), -1 , first) ;
						while((cubeLevel = (RolapLevel) cubeLevel.getParentLevel())!=null && cubeLevel.getName().indexOf("All")<0){
							n++;
							FirstTitle first2 = new FirstTitle();
							first2.setName(cubeLevel.getName());
							first2.setLevel(cubeLevel.getUniqueName()) ;
							if(level.getFirstTitle().size()>firstTitle.size()-i){
								addFirstTitle(level.getFirstTitle(),  firstTitle.size()-n, first2) ;
							}else{
								addFirstTitle(level.getFirstTitle() , 0 , first2) ;
							}
						}
					}else{
						boolean isHave = false;
						for(FirstTitle fr : level.getFirstTitle()){
							if(fr.getLevel().equals(cubeLevel.getUniqueName())){
								isHave = true;
								break;
							}
						}
						if(!isHave){
							FirstTitle first = new FirstTitle();
							first.setName(cubeLevel.getName());
							first.setLevel(cubeLevel.getUniqueName()) ;
							addFirstTitle(level.getFirstTitle(), -1 , first ) ;
							while((cubeLevel = (RolapLevel) cubeLevel.getParentLevel())!=null && cubeLevel.getName().indexOf("All")<0){
								n++;
								FirstTitle first2 = new FirstTitle();
								first2.setName(cubeLevel.getName());
								first2.setLevel(cubeLevel.getUniqueName()) ;
								if(level.getFirstTitle().size()>firstTitle.size()-i){
									addFirstTitle(level.getFirstTitle() , firstTitle.size()-n, first2) ;
								}else{
									addFirstTitle(level.getFirstTitle() ,0,  first2) ;
								}
								
							}
						}
					}
				}else if(member.getLevel() instanceof RolapLevel && cubeLevel.getName().equals("MeasuresLevel")){	//指标列
					if(level.getFirstTitle()==null){
						level.setFirstTitle(firstTitle);
						FirstTitle first = new FirstTitle();
						first.setName(RivuDataContext.CUBE_TITLE_MEASURE);
						first.setLevel(cubeLevel.getUniqueName()) ;
						addFirstTitle(level.getFirstTitle(), -1 , first) ;
						while((cubeLevel = (RolapLevel) cubeLevel.getParentLevel())!=null && cubeLevel.getName().indexOf("All")<0){
							n++;
							FirstTitle first2 = new FirstTitle();
							first2.setName(cubeLevel.getName());
							first2.setLevel(cubeLevel.getUniqueName()) ;
							if(level.getFirstTitle().size()>firstTitle.size()-i){
								addFirstTitle(level.getFirstTitle(),  firstTitle.size()-n, first2) ;
							}else{
								addFirstTitle(level.getFirstTitle() , 0 , first2) ;
							}
						}
					}else{
						boolean isHave = false;
						for(FirstTitle fr : level.getFirstTitle()){
							if(fr.getLevel().equals(cubeLevel.getUniqueName())){
								isHave = true;
								break;
							}
						}
						if(!isHave){
							FirstTitle first = new FirstTitle();
							first.setName(RivuDataContext.CUBE_TITLE_MEASURE);
							first.setLevel(cubeLevel.getUniqueName()) ;
							addFirstTitle(level.getFirstTitle(), -1 , first ) ;
							while((cubeLevel = (RolapLevel) cubeLevel.getParentLevel())!=null && cubeLevel.getName().indexOf("All")<0){
								n++;
								FirstTitle first2 = new FirstTitle();
								first2.setName(cubeLevel.getName());
								first2.setLevel(cubeLevel.getUniqueName()) ;
								if(level.getFirstTitle().size()>firstTitle.size()-i){
									addFirstTitle(level.getFirstTitle() , firstTitle.size()-n, first2) ;
								}else{
									addFirstTitle(level.getFirstTitle() ,0,  first2) ;
								}
								
							}
						}
					}
				}
				
		
				if (strb.length() > 0) {
					strb.append("l__HHHH-A-HHHH__l");
				}
				strb.append(member.getUniqueName().substring(member.getUniqueName().indexOf(".")+1).replaceAll("\\.\\[\\]", "______R3_SPACE").replaceAll("\\]\\.\\[", "l__HHHH-A-HHHH__l").replaceAll("[\\]\\[]", ""));
			}
			valueStr.add(strb.toString().replace("#null", " "));//替换掉所有的#null为空字符串
		}
		int depth = 0 ;
		for (int inx = 0 ; inx< valueStr.size() ; inx++) {
			String value = valueStr.get(inx) ;
			Level currentlevel = level;
			String[] levels = value.replaceAll("Measures______", "").split("l__HHHH-A-HHHH__l");
			if(levels.length>depth){
				depth = levels.length-1 ;
			}
			for (int i = 0 ; i < levels.length; i++) {
				boolean found = false;
				if (currentlevel.getChilderen() == null) {
					currentlevel.setChilderen(new ArrayList<Level>());
				}
				if(!levels[i].equals("R3_SPACE")){
					for (Level lv : currentlevel.getChilderen()) {
						if (levels[i].equals(lv.getName())) {
							currentlevel = lv;
							found = true;
							break;
						}
					}
					if (!found) {
						currentlevel.getChilderen().add(currentlevel = new Level(levels[i], level.getLeveltype() , currentlevel , levels.length - i , inx));
						if(i == levels.length-1){
							if(currentlevel.getChilderen()==null){
								currentlevel.setChilderen(new ArrayList<Level>()) ;
							}
							currentlevel.setIndex(inx) ;
							currentlevel.getChilderen().add(new Level("R3_TOTAL" , level.getLeveltype() , currentlevel , levels.length - i , inx));
						}
						if(level.getFirstTitle()!=null && level.getFirstTitle().size()>i){
							currentlevel.setDimname(level.getFirstTitle().get(i).getName()) ;
						}
					}else{
						if(i == levels.length-1){
							if(currentlevel.getChilderen()==null){
								currentlevel.setChilderen(new ArrayList<Level>()) ;
							}
							currentlevel.setIndex(inx) ;
							currentlevel.getChilderen().add(new Level("R3_TOTAL" , level.getLeveltype() , currentlevel , levels.length - i , inx));
						}
					}
				}else{
					currentlevel.getChilderen().add(currentlevel = new Level("", level.getLeveltype() , currentlevel , levels.length - i , inx));
					if(i == levels.length-1){
						if(currentlevel.getChilderen()==null){
							currentlevel.setChilderen(new ArrayList<Level>()) ;
						}
						currentlevel.setIndex(inx) ;
						currentlevel.getChilderen().add(new Level("R3_TOTAL" , level.getLeveltype() , currentlevel , levels.length - i , inx));
					}
					if(level.getFirstTitle()!=null && level.getFirstTitle().size()>i){
						currentlevel.setDimname(level.getFirstTitle().get(i).getName()) ;
					}
				}
			}
		}

		iterator(valueMap, level, level.getLeveltype());
		level.setDepth(depth) ;
		for(Level temp : level.getChilderen()){
			temp.setParent(level) ;
		}
		sumRowspanColspan(level);
		level.init() ;	//格式化
		return level;
	}
	/**
	 * 
	 * @param firstTitleList
	 * @param title
	 */
	private void addFirstTitle(List<FirstTitle> firstTitleList , int index , FirstTitle title){
		boolean found = false ;
		for(FirstTitle firstTitle : firstTitleList){
			if(firstTitle.getLevel().equals(title.getLevel())){
				found = true; 
				break ;
			}
		}
		if(!found){
			if(index<0){
				firstTitleList.add(title) ;
			}else{
				firstTitleList.add(index , title) ;
			}
		}
	}
	/**
	 * 处理 合计字段
	 * @param level
	 */
	private void processSum(Level level , List<List<ValueData>> valueDataList , Level root){
		for(int i=0 ; level.getChilderen()!=null && i<level.getChilderen().size() ; i++){
			Level child = level.getChilderen().get(i) ;
//			child.setIndex(i) ;
			if(child.getName().equals("R3_TOTAL") && !child.isTotal() && level.getIndex() < valueDataList.size()){
				child.setName("合计");
				child.setTotal(true) ;
				child.setFirst(i==0) ;
				if(level.getChilderen().size()>1 && level.getParent()!=null){
					child.setValueData(valueDataList.get(level.getIndex())) ;
					if(level.getParent().getChilderen().size()>0){
//						for(int inx = 0 ; inx < level.getParent().getChilderen().size() ; inx++){
//							if(level.getParent().getChilderen().get(inx).getName().equals(child.getParent().getName())){
////								child.setParent(child.getParent().getParent()) ;
////								level.getParent().getChilderen().add(inx+1 , child);
//								break ;
//							}
//						}
						child.setDepth(getDepth(child)) ;
						child.setColspan(root.getFirstTitle().size() - child.getDepth()) ;
//						level.getChilderen().remove(i--) ;
					}
					
				}else{
					if(valueDataList.size()>child.getIndex()){
						level.setValueData(valueDataList.get(level.getIndex())) ;
					}
					level.setChilderen(null) ;
				}
			}else{
				processSum(child , valueDataList , root) ;
			}
		}
	}
	
	private void pagetTotalProcess(CubeData data , AnalyzerReportModel model , Cube cube){
		ArrayList<ValueData> totalValueList = new ArrayList<ValueData>() ;
		if (data.getCol().getTitle()!=null && data.getCol().getTitle().size()>0) {
			for (int i=0 ; i<data.getCol().getTitle().get(data.getCol().getTitle().size()-1).size(); i++) {
				Level  measurename = data.getCol().getTitle().get(data.getCol().getTitle().size()-1).get(i) ;
				ValueData valueData = new ValueData(measurename.getName(), null , null , "total") ;
				for(CubeMeasure measure : cube.getMeasure()){
					if(measurename.getName().equals(measure.getName())){
						if(data.getData().size()>0){
							for(int rows = 0 ; rows < data.getData().size() ; rows++){
								if(i<data.getData().get(rows).size()){
									ValueData value = data.getData().get(rows).get(i) ;
									if(value!=null && value.getValue()!=null){
										if(valueData.getValue()==null){
											valueData.setValue(value.getValue()) ;
										}else{
											if("sum".equals(measure.getAggregator()) || "avg".equals(measure.getAggregator()) || "count".equals(measure.getAggregator()) || "distinct-count".equals(measure.getAggregator())){
												if(value.getValue() instanceof Integer){
													valueData.setValue(new Integer((Integer)(value.getValue()) + (Integer)(valueData.getValue()))) ;
												}else if(value.getValue() instanceof Float){
													valueData.setValue(new Float((Float)(value.getValue()) + (Float)valueData.getValue())) ;
												}else if(value.getValue() instanceof Double){
													valueData.setValue(new Double((Double)(value.getValue()) + (Double)(valueData.getValue()))) ;
												}else if(value.getValue() instanceof Number){
													valueData.setValue(new Double(((Number)(value.getValue())).doubleValue() + (Double)(valueData.getValue()))) ;
												}
											}else if("max".equals(measure.getAggregator())){
												if(value.getValue() instanceof Integer && ((Integer)(value.getValue()) > (Integer)(valueData.getValue()))){
													valueData.setValue((Integer)(value.getValue())) ;
												}else if((valueData.getValue()) instanceof Float && ((Float)(value.getValue()) > (Float)(valueData.getValue()))){
													valueData.setValue((Float)(value.getValue())) ;
												}else if(value.getValue() instanceof Double && ((Double)(value.getValue()) > (Double)(valueData.getValue()))){
													valueData.setValue((Double)(value.getValue())) ;
												}else if(value.getValue() instanceof Number && (((Number)(value.getValue())).doubleValue() > ((Number)(valueData.getValue())).doubleValue())){
													valueData.setValue((Number)(value.getValue())) ;
												}
											}else if("min".equals(measure.getAggregator())){
												if(value.getValue() instanceof Integer && ((Integer)(value.getValue()) < (Integer)(valueData.getValue()))){
													valueData.setValue((Integer)(value.getValue())) ;
												}else if(value.getValue() instanceof Float && ((Float)(value.getValue()) < (Float)(valueData.getValue()))){
													valueData.setValue((Float)(value.getValue())) ;
												}else if(value.getValue() instanceof Double && ((Double)(value.getValue()) < (Double)(valueData.getValue()))){
													valueData.setValue((Double)(value.getValue())) ;
												}else if(value.getValue() instanceof Number && (((Number)(value.getValue())).doubleValue() < ((Number)(valueData.getValue())).doubleValue())){
													valueData.setValue((Number)(value.getValue())) ;
												}
											}
										}
									}
								}
							}
							
							if("avg".equals(measure.getAggregator())){
								if(valueData.getValue() instanceof Integer){
									valueData.setValue((int)new Integer(((Integer)(valueData.getValue()))/data.getData().size())) ;
								}else if(valueData.getValue() instanceof Float){
									valueData.setValue((float)((int)((new Float(((Float)(valueData.getValue()))/data.getData().size()))*100)) / 100) ;
								}else if(valueData.getValue() instanceof Double){
									valueData.setValue( ((double)((int)((new Double(((Double)(valueData.getValue()))/data.getData().size()))*100)))/100 ) ;
								}else if(valueData.getValue() instanceof Number){
									valueData.setValue((double)((int)(new Double((((Number)(valueData.getValue())).doubleValue())/data.getData().size())*100)) / 100) ;
								}
							}
						}
 						break ;
					}
				}
				if(valueData.getValue()==null){
					valueData.setValue("");
				}
				if(valueData.getValue()!=null){
					valueData.setForamatValue(valueData.getValue().toString()) ;
				}
				totalValueList.add(valueData);
			}
		}
		if(data.getRow()!=null && data.getRow().getTitle() !=null && data.getRow().getTitle().size()>0 && data.getRow().getTitle().size()>0){
			data.getRow().getTitle().get(0).add(new Level("合计", "R3_TOTAL", data.getRow().getLeveltype(), 1, data.getRow().getFirstTitle().size(), totalValueList, true, false, 0)) ;
		}
		
		if(data.getData()!=null){
			data.getData().add(totalValueList) ;
		}
	}
	
	/*
	 * 
	 */
	private void processTitle(Level level , Level root){
		for(int i=0 ; level.getChilderen()!=null && i<level.getChilderen().size() ; i++){
			Level child = level.getChilderen().get(i) ;
			int depth = getDepth(child) ;
			if(depth>=0){
				if(root.getTitle().size()<=depth){
					root.getTitle().add(new ArrayList<Level>()) ;
				}
				Level tempLevel = new Level(child.getName() , child.getNameValue() , child.getLeveltype() , child.getRowspan() , child.getColspan() , child.getValueData() , child.isTotal() , child.isFirst()) ;
				tempLevel.setParent(child) ;
				root.getTitle().get(depth).add(tempLevel)  ;
			}
			if((child.getNameValue().equals("R3_TOTAL") && root.getFirstTitle()!=null && (depth+1) < root.getFirstTitle().size()) || (child.getChilderen()==null && root.getFirstTitle()!=null && (depth+1) < root.getFirstTitle().size())){
				child.setChilderen(new ArrayList<Level>()) ;
				child.setColspan(root.getFirstTitle().size() - depth);
				if(root.getTitle()!=null && root.getTitle().size()>depth){
					for(Level title : root.getTitle().get(depth)){
						if(title.getName().equals(child.getName())){
							title.setColspan(child.getColspan()) ;
						}
					}
				}
				Level tempLevel = new Level("TOTAL_TEMP" , "R3_TOTAL" , child.getLeveltype() ,child.getRowspan() ,child.getColspan(), child.getValueData() , child.isTotal() , child.isFirst() , child.getDepth()+1) ;
				tempLevel.setParent(child) ;
				child.getChilderen().add(tempLevel) ;
				child.setValue(null) ;
			}
			processTitle(child , root);
		}
	}
	
	private int getDepth(Level level){
		int depth = 0 ;
		while((level = level.getParent())!=null){
			depth++ ;
		}
		return depth - 1 ;
	}
	/**
	 * 处理行列合并单元格
	 * @param level
	 */
	private void sumRowspanColspan(Level level) {
		if(level.getChilderen()!=null){
			for(int i=0 ; level.getChilderen()!=null && i<level.getChilderen().size() ; i++){
				Level lv = level.getChilderen().get(i) ;
				if(lv.getColspan()==0 && lv.getRowspan()==0){
					sumRowspanColspan(lv);
				}
				if(level.getLeveltype().equals("col")){
					level.setColspan(level.getColspan()+lv.getColspan()) ;
				}else{
					level.setRowspan(level.getRowspan()+lv.getRowspan()) ;
				}
			}
		}else{
			if(level.getLeveltype().equals("col")){
				level.setColspan(1) ;
			}else{
				level.setRowspan(1) ;
			}
		}
	}

	/**
	 * 
	 * @param axes
	 * @param axis
	 * @param pos
	 * @param result
	 * @param dataList
	 * @param rowno
	 */
	private void getRowData(Axis[] axes, int axis, int[] pos, Result result, List<List<ValueData>> dataList, int rowno , Position position , CubeData cubeData) {
		if (axis < 0) {
			if (dataList.size() <= rowno || dataList.get(rowno) == null) {
				dataList.add(new ArrayList<ValueData>());
			}
			Cell cell = result.getCell(pos) ;
			ValueData valueData  = new ValueData(cell.getValue(), cell.getFormattedValue(), null  , cell.canDrillThrough(), cell.getDrillThroughSQL(true) , position!=null && position.size()>0 ? position.get(position.size()-1).getName():"" , cell.getCachedFormatString()) ;
			int rows = 0 ;
			valueData.setRow(getParentLevel(cubeData.getRow() , rowno, rows)) ;
			dataList.get(rowno).add(valueData);
		} else {
			Axis _axis = axes[axis];
			List<Position> positions = _axis.getPositions();
			for (int i = 0; i < positions.size(); i++) {
				Position posit = positions.get(i) ;
				pos[axis] = i;
				if (axis == 0) {
					int row = axis + 1 < pos.length ? pos[axis + 1] : 0;
					rowno = row;
				}
				getRowData(axes, axis - 1, pos, result, dataList, rowno , posit , cubeData);
			}
		}
	}
	private Level getParentLevel(Level level , int rowno , int rows){
		if(level!=null && level.getChilderen()!=null){
			for(Level lv : level.getChilderen()){
				rows = rows + lv.getRowspan() ;
				if(rows==rowno){
					while(level.getChilderen()!=null && level.getChilderen().size()>0){
						level = level.getChilderen().get(level.getChilderen().size()-1) ;
					}
				}
				if(rows>rowno){
					rows = rows - lv.getRowspan() ;
					return getParentLevel(lv , rowno , rows) ;
				}
			}
		}
		return level ;
	}
	/**
	 * 更新缓存
	 */
	public void refresh(String ds , Cube cb){
		/**
		 * 更新缓存
		 */
		AggregationManager.instance().getCacheControl(null, null).flushSchemaCache();
	}
	
	/**
	 * 如果请求带有参数 则更改用户识别码 查询对应数据源
	 * @param request
	 * @param model
	 * @param parseParam
	 * @throws Exception
	 */
	/**
	 * 如果请求带有参数 则更改用户识别码 查询对应数据源
	 * @param request
	 * @param model
	 * @param parseParam
	 * @throws Exception
	 */
	private void replaceDataBase(AnalyzerReportModel model , HttpServletRequest request , boolean parseParam) throws Exception{
		String userCode = request.getParameter("R_c");
		if(userCode!=null && !"".equals(userCode)){}
	}

	@Override
	public Date getDate() {
		// TODO Auto-generated method stub
		return new Date();
	}

	public Database getDatabase() {
		return database;
	}

	public void setDatabase(Database database) {
		this.database = database;
	}
	@Override
	public void getRSData(AnalyzerReportModel model,
			Map<String, Object> requestParamValues, Cube cube,
			HttpServletRequest request, boolean parseParam,
			QueryText queryText, ExportFile export) throws Exception {
		/**
		 * 等待处理
		 */
	}
	@Override
	public ReportData getVData(AnalyzerReportModel model,
			Map<String, Object> requestParamValues, Cube cube,
			HttpServletRequest request, boolean parseParam,
			QueryText queryText, QueryLog queryLog) throws Exception {
		// TODO Auto-generated method stub
		return this.getData(model, requestParamValues, cube, request, parseParam, queryText, queryLog);
	}
}
